package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"hospital/models"
	"hospital/pkg"
	"time"
)

type DoctorController struct {
	beego.Controller
}

type JsonR struct {
	Conde int         `json:"conde"`
	Msg   string      `json:"msg"`
	Data  interface{} `json:"data"`
}

func (c *DoctorController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	key := "lock-" + username
	count, _ := models.Rdb.Get(key).Int()
	if count >= 3 {
		c.Data["json"] = JsonR{
			Conde: 500,
			Msg:   "连续登录次数过多请两个小时候在登录",
			Data:  nil,
		}
		c.ServeJSON()
		return
	}
	var user models.Doctor
	err := models.DB.Model(&models.Doctor{}).Where("username = ?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Conde: 500,
			Msg:   "没有此用户",
			Data:  nil,
		}
		c.ServeJSON()
		return
	}

	if user.Password == pkg.Md5Password(password) {
		c.Data["json"] = JsonR{
			Conde: 200,
			Msg:   "登录成功",
			Data:  nil,
		}
		c.ServeJSON()
		return
	} else {
		models.Rdb.Incr(key)
		models.Rdb.Expire(key, time.Hour*2)
		c.Data["json"] = JsonR{
			Conde: 500,
			Msg:   "密码错误登录失败",
			Data:  nil,
		}
		c.ServeJSON()
		return
	}
}
